//
// Created by 李望轩 on 2020/11/20.
//
/*
 * 读Json文件中的数组
 */

#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
#include"../LeCJson/cJSON.h"


size_t get_file_size(const char *filepath) {
    if (filepath == NULL)
        return 0;
    struct stat filestat;
    memset(&filestat, 0, sizeof(struct stat));
    if (0 == stat(filepath, &filestat))
        return filestat.st_size;
    else
        return 0;
}

char *read_file_to_buf(const char *filepath) {
    if (NULL == filepath) {
        return NULL;
    }
    size_t size = get_file_size(filepath);
    if (0 == size)
        return NULL;

    char *buf = malloc(size + 1);
    if (NULL == buf)
        return NULL;
    memset(buf, 0, size + 1);

    FILE *fp = fopen(filepath, "r");
    size_t readSize = fread(buf, 1, size, fp);
    if (readSize != size) {
        free(buf);
        buf = NULL;
    }

    buf[size] = 0;
    return buf;
}

cJSON *prepare_parse_json(const char *filePath) {
    if (NULL == filePath) {
        return NULL;
    }
    char *buf = read_file_to_buf(filePath);
    if (NULL == buf) {
        return NULL;
    }
    cJSON *pTemp = cJSON_Parse(buf);
    free(buf);
    buf = NULL;
    return pTemp;
}

cJSON *LeReadJsonList(int Flag, cJSON *root) {
    /*
     * Flag为假时读取Book 为真时读取Stu
     */

    char *filename = "../Data/Data.json";
    root = prepare_parse_json(filename);
    if (NULL == root) {
        //Json文件读取失败或为空
        return NULL;
    }

    //为0时读取Book 为1时读取Stu
    char Str[] = "Book";
    if (Flag)strcpy(Str, "Stu");

    cJSON *Json_List = cJSON_GetObjectItem(root, Str);
    if (!Json_List) {
        //List读取失败
        return NULL;
    }
    return Json_List;
}